<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>AJAX 解析html、xml、json</title>
    <link rel="shortcut icon" href="../../../../favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="../../../../src/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../css/ajax.css">
</head>

<body>
    <div class="container">
        <h2>html 中的的容器</h2>
        <pre><code><span class="nt">&lt;section</span> <span class="na">id=</span><span class="s">"content"</span><span class="nt">&gt;&lt;/section&gt;</span></code></pre>
        <h2>一丶AJAX 解析 html</h2>
        <pre><code><span class="k">var</span> xhr = new XMLHttpRequest();                 <span class="c">// 创建XMLHttpRequest对象</span>

xhr.onload = <span class="k">function</span>() {                       <span class="c">// 响应加载后</span>
    <span class="c">// 以下条件检查在本地不起作用 - 仅在服务器上</span>
    if(xhr.status === 200) {                       <span class="c">// 如果服务器状态正常</span>
    document.getElementById('content').innerHTML = xhr.<span class="s">responseText</span>; <span class="c">// 更新页面数据</span>
    }
};

xhr.open('GET', 'data/data.html', true);        <span class="c">// 准备请求</span>
xhr.send(null);        <span class="c">// 发送请求</span></code></pre>
        <h3>响应中的头部信息<code>Content-Type: text/html; charset=UTF-8</code>，响应体是下面的部分：</h3>
        <pre><code><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"event"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;img</span> <span class="na">src=</span><span class="s">"img/map-ca.png"</span> <span class="na">alt=</span><span class="s">"Map of California"</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;p&gt;&lt;b&gt;</span> San Francisco, CA <span class="nt">&lt;/b&gt;&lt;br&gt;</span>
    May 1 <span class="nt">&lt;/p&gt;</span>
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"event"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;img</span> <span class="na">src=</span><span class="s">"img/map-tx.png"</span> <span class="na">alt=</span><span class="s">"Map of Texas"</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;p&gt;&lt;b&gt;</span> Austin, TX <span class="nt">&lt;/b&gt;&lt;br&gt;</span>
    May 15 <span class="nt">&lt;/p&gt;</span>
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"event"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;img</span> <span class="na">src=</span><span class="s">"img/map-ny.png"</span> <span class="na">alt=</span><span class="s">"Map of New York"</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;p&gt;&lt;b&gt;</span> New York, NY <span class="nt">&lt;/b&gt;&lt;br&gt;</span>
    May 30 <span class="nt">&lt;/p&gt;</span>
<span class="nt">&lt;/div&gt;</span></code></pre>

        <h2>二丶AJAX 解析 xml</h2>
        <pre><code><span class="k">var</span> xhr = new XMLHttpRequest();        <span class="c">// 创建XMLHttpRequest对象</span> 

xhr.onload = <span class="k">function</span>() {        <span class="c">// 响应加载后</span>
    if (xhr.status === 200) {        <span class="c">// 如果服务器状态正常</span>

        <span class="k">var</span> response = xhr.<span class="s">responseXML</span>;        <span class="c">// 从服务器获取XML</span>                      
        <span class="k">var</span> events = response.getElementsByTagName('event'); 

        for (<span class="k">var</span> i = 0; i &lt; events.length; i++) {        <span class="c">// 遍历 xml 数据</span>          
        var container, image, location, city, newline;      
        container = document.createElement('div');          
        container.className = 'event';                      

        image = document.createElement('img');              
        image.setAttribute('src', getNodeValue(events[i], 'map'));
        image.setAttribute('alt', getNodeValue(events[i], 'location'));
        container.appendChild(image);

        location = document.createElement('p');            
        city = document.createElement('b');
        newline = document.createElement('br');
        city.appendChild(document.createTextNode(getNodeValue(events[i], 'location')));
        location.appendChild(newline);
        location.insertBefore(city, newline);
        location.appendChild(document.createTextNode(getNodeValue(events[i], 'date')));
        container.appendChild(location);

        document.getElementById('content').appendChild(container);
        }
    }

    <span class="k">function</span> getNodeValue(obj, tag) {        <span class="c">// 从XML获取内容</span>                   
    <span class="k">return</span> obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
    }
};

xhr.open('GET', 'data/data.xml', true);        <span class="c">// 准备请求</span>             
xhr.send(null);        <span class="c">// 发送请求</span> </code></pre>
        <h3>响应头中信息：<code>Content-Type: application/xml</code>，响应体中信息：</h3>
        <pre><code><span class="c">&lt;?xml version="1.0" encoding="utf-8" ?&gt;</span>
<span class="nt">&lt;events&gt;</span>
    <span class="nt">&lt;event&gt;</span>
    <span class="nt">&lt;location&gt;</span>San Francisco, CA<span class="nt">&lt;/location&gt;</span>
    <span class="nt">&lt;date&gt;</span>May 1<span class="nt">&lt;/date&gt;</span>
    <span class="nt">&lt;map&gt;</span>img/map-ca.png<span class="nt">&lt;/map&gt;</span>
    <span class="nt">&lt;/event&gt;</span>
    <span class="nt">&lt;event&gt;</span>
    <span class="nt">&lt;location&gt;</span>Austin, TX<span class="nt">&lt;/location&gt;</span>
    <span class="nt">&lt;date&gt;</span>May 15<span class="nt">&lt;/date&gt;</span>
    <span class="nt">&lt;map&gt;</span>img/map-tx.png<span class="nt">&lt;/map&gt;</span>
    <span class="nt">&lt;/event&gt;</span>
    <span class="nt">&lt;event&gt;</span>
    <span class="nt">&lt;location&gt;</span>New York, NY<span class="nt">&lt;/location&gt;</span>
    <span class="nt">&lt;date&gt;</span>May 30<span class="nt">&lt;/date&gt;</span>
    <span class="nt">&lt;map&gt;</span>img/map-ny.png<span class="nt">&lt;/map&gt;
    <span class="nt">&lt;/event&gt;</span>
<span class="nt">&lt;/events&gt;</span></code></pre>

        <h2>三丶AJAX 解析 json</h2>
        <pre><code><span class="k">var</span> xhr = new XMLHttpRequest();                 <span class="c">// 创建XMLHttpRequest对象</span>

xhr.onload = function() {                       <span class="c">// 当状态发生变化时</span>
    if(xhr.status === 200) {                     <span class="c">// 如果服务器状态正常</span>
        responseObject = JSON.<span class="s">parse</span>(xhr.<span class="s">responseText</span>);

        <span class="c">// 使用新内容构建字符串（也可以使用DOM操作）</span>
        <span class="k">var</span> newContent = '';
        for (<span class="k">var</span> i = 0; i &lt; responseObject.events.length; i++) {   <span class="c">// 遍历结果</span>
            newContent += '&lt;div class="event"&gt;';
            newContent += '&lt;img src="' + responseObject.events[i].map + '" ';
            newContent += 'alt="' + responseObject.events[i].location + '" /&gt;';
            newContent += '&lt;p&gt;&lt;b&gt;' + responseObject.events[i].location + '&lt;/b&gt;&lt;br&gt;';
            newContent += responseObject.events[i].date + '&lt;/p&gt;';
            newContent += '&lt;/div&gt;';
        }

        <span class="c">// 使用新内容更新页面</span>
        document.getElementById('content').innerHTML = newContent;
    }
};

xhr.open('GET', 'data/data.json', true);        <span class="c">// 准备请求</span>  
xhr.send(null);                                 <span class="c">// 发送请求</span></code></pre>

        <h3>响应头内容：<code>Content-Type: application/json</code>，响应体内容：</h3>
        <pre><code>{
    <span class="s">"events"</span>: [
        {
            <span class="s">"location"</span>: <span class="s">"San Francisco, CA"</span>,
            <span class="s">"date"</span>: <span class="s">"May 1"</span>,
            <span class="s">"map"</span>: <span class="s">"img/map-ca.png"</span>
        },
        {
            <span class="s">"location"</span>: <span class="s">"Austin, TX"</span>,
            <span class="s">"date"</span>: <span class="s">"May 15"</span>,
            <span class="s">"map"</span>: <span class="s">"img/map-tx.png"</span>
        },
        {
            <span class="s">"location"</span>: <span class="s">"New York, NY"</span>,
            <span class="s">"date"</span>: <span class="s">"May 30"</span>,
            <span class="s">"map"</span>: <span class="s">"img/map-ny.png"</span>
        }
    ]
}</code></pre>

        <h2>四丶跨域之 jsonp，ajax 的核心是通过 XmlHttpRequest 获取非本页内容，而 jsonp 的核心则是动态添加</h2>
        <h3><code>body</code>中的结构：</h3>
        <pre><code><span class="nt">&lt;script</span> <span class="na">src=</span><span class="s">"js/data-jsonp.js"</span> <span class="nt">&gt;&lt;/script&gt;</span>
<span class="nt">&lt;script</span> <span class="na">src=</span><span class="s">"http://htmlandcssbook.com/js/jsonp.js?callback=showEvents"</span> <span class="nt">&gt;&lt;/script&gt;</span></code></pre>
        <h4><code>"js/data-jsonp.js"</code>中的内容</h4>
        <pre><code><span class="k">function</span> <span class="s">showEvents</span>(data) {                           <span class="c">// JSON加载时的回调函数</span>
    <span class="k">var</span> newContent = '';                              <span class="c">// 变量来保存HTML</span>

    <span class="c">// 用新内容构建字符串（也可以使用DOM操作）</span>
    for (<span class="k">var</span> i = 0; i &lt; data.events.length; i++) {    <span class="c">// 遍历数据</span>
        newContent += '&lt;div class="event"&gt;';
        newContent += '&lt;img src="' + data.events[i].map + '" ';
        newContent += 'alt="' + data.events[i].location + '" /&gt;';
        newContent += '&lt;p&gt;&lt;b&gt;' + data.events[i].location + '&lt;/b&gt;&lt;br&gt;';
        newContent += data.events[i].date + '&lt;/p&gt;';
        newContent += '&lt;/div&gt;';
    }

    <span class="c">// 用新内容更新页面</span>
    document.getElementById('content').innerHTML = newContent;
}</code></pre>
        <h4><code>"http://htmlandcssbook.com/js/jsonp.js"</code>中的内容：</h4>
<pre><code>{
        <span class="s">"events"</span>: [
            {
                <span class="s">"location"</span>: <span class="s">"San Francisco, CA"</span>,
                <span class="s">"date"</span>: <span class="s">"May 1"</span>,
                <span class="s">"map"</span>: <span class="s">"img/map-ca.png"</span>
            },
            {
                <span class="s">"location"</span>: <span class="s">"Austin, TX"</span>,
                <span class="s">"date"</span>: <span class="s">"May 15"</span>,
                <span class="s">"map"</span>: <span class="s">"img/map-tx.png"</span>
            },
            {
                <span class="s">"location"</span>: <span class="s">"New York, NY"</span>,
                <span class="s">"date"</span>: <span class="s">"May 30"</span>,
                <span class="s">"map"</span>: <span class="s">"img/map-ny.png"</span>
            }
        ]
}</code></pre>
        <h3>因为 jsonp 不是 XHR，查看的时候点 ALL，查看<code>jsonp.js?callback=showEvents</code>可以发现，就是在调用<code>showEvents</code>：</h3>
        <pre><code>showEvents({
  <span class="s">"events"</span>: [
    {
        <span class="s">"location"</span>: <span class="s">"San Francisco, CA"</span>,
        <span class="s">"date"</span>: <span class="s">"May 1"</span>,
        <span class="s">"map"</span>: <span class="s">"img/map-ca.png"</span>
    },
    {
        <span class="s">"location"</span>: <span class="s">"Austin, TX"</span>,
        <span class="s">"date"</span>: <span class="s">"May 15"</span>,
        <span class="s">"map"</span>: <span class="s">"img/map-tx.png"</span>
    },
    {
        <span class="s">"location"</span>: <span class="s">"New York, NY"</span>,
        <span class="s">"date"</span>: <span class="s">"May 30"</span>,
        <span class="s">"map"</span>: <span class="s">"img/map-ny.png"</span>
    }
  ]
});</code></pre>
        <h2>五丶小结</h2>
        <ul>
            <li>在使用<code>xhr</code>的时候，除了<code>onload</code>方法，还可以使用<code>onreadystatechange</code>方法，但是里面内容有一些改变</li>
            <li>
                <pre><code><span class="k">var</span> xmlhttp = new XMLHttpRequest();
xmlhttp.<span class="s">onreadystatechange</span> = function() {
    <span class="c">// onreadystatechange 只要返回的状态码变化时就回调一次函数，而 onload 只有状态码为 4 时才能回调一次函数</span>
    if (this.readyState == 4 && this.status == 200) {
        myArr = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myArr[1];
    }
};
xmlhttp.open("GET", "/try/ajax/json_demo_array.txt", true);
xmlhttp.send();</code></pre>
            </li>
            <li>凡是拥有<code>"src"</code>这个属性的标签都拥有跨域的能力，比如 <code>&lt;\script&gt;</code> 、<code>&lt;\img&gt;</code> 、<code>&lt;\iframe&gt;</code></li>
        </ul>
    </div>
</body>

</html>